package com.main.usermanagement.domain.user.event.publish;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.main.crossdomaineventmanagement.event.core.EventPublisher;
import com.main.crossdomaineventmanagement.event.model.EventMessage;
import com.main.usermanagement.application.event.publish.AddAccountEventPublisher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class AddAccountEventImpl implements AddAccountEventPublisher {

    @Autowired
    @Qualifier("rocketMQTxEventPublisher")
    private  EventPublisher eventPublisher;

    @Override// 使用声明式事务管理，明确传播行为
    @Transactional
     public void publishAddAccountEvent(Long userId, String name,Long clientId){
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("userId", userId);
            payload.put("name", name);
            payload.put("clientId", clientId);
            String payloadJson = new ObjectMapper().writeValueAsString(payload);
            EventMessage event = new EventMessage("ADD_ACCOUNT", "user-management", payloadJson);
            log.info("开始发送创建账号消息,用户ID：{}", userId);
            eventPublisher.publish(event);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize event", e);
        }
    }
  
}